<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>
  <div class="public_main">
    <div class="left_tree">
      <!-- <el-input v-model="queryParams.sectionName" placeholder="请输入部段名称" /> -->
      <el-input v-model="sectionName" size="small" placeholder="请输入部段名称" @keyup.enter="getTreeDate" :suffix-icon="Search" />
      <el-tree
        :data="treeData"
        :props="defaultProps"
        :default-expand-all="false"
        @node-click="treeSelect"
        :expand-on-click-node="false"
        lazy
        :load="loadNode"
        @node-contextmenu="rightClick"
      >
        <template #default="{ node, data }">
          <span class="custom-tree-node">
            <span>{{ node.label }}</span>
            <span v-if="data.necessaryItemsCount > 0" style="margin-left: 5px; color: #ccc">
              [<a style="color: #409eff; font-size: 12px">必备件数: {{ data.necessaryItemsCount }} </a>]
            </span>
          </span>
        </template>
      </el-tree>
    </div>
    <div class="right_table">
      <div class="query">
        <el-form inline ref="queryFormRef" :model="queryParams" label-width="100px" size="small">
          <el-form-item label="机型:">
            <el-select v-model="queryParams.modelNumber" placeholder="请选择机型">
              <el-option v-for="item in modelList" :label="item.name" :value="item.mark" :key="item.mark"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="批次号:">
            <el-input v-model="queryParams.batchNumber" placeholder="请输入批次号" />
          </el-form-item>
          <el-form-item label="部段号:">
            <el-input v-model="queryParams.sectionNumber" placeholder="请输入部段号" />
          </el-form-item>
          <el-form-item label="部段名称:">
            <el-input v-model="queryParams.sectionName" placeholder="请输入部段名称" />
          </el-form-item>
          <el-form-item label="组件号:">
            <el-input v-model="queryParams.componentNumber" placeholder="请输入组件号" />
          </el-form-item>
          <!-- <el-form-item label="组件名称:">
            <el-input v-model="queryParams.fileName" placeholder="请输入组件名称" />
          </el-form-item> -->
          <el-form-item class="query_btns">
            <el-button size="small" type="primary" icon="search" @click="doQuery">查询</el-button>
            <el-button size="small" type="default" icon="refresh" @click="doReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="table_div">
        <el-button size="small" type="primary" class="upload_btn" plain icon="Plus" @click="handleVisible('add')">新增</el-button>
        <el-button size="small" type="danger" class="upload_btn" plain icon="Delete" @click="handleDelete()">删除</el-button>
        <el-table :data="tableData" v-loading="loading" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="必备件上传日期" align="center" prop="createTime" width="120" show-overflow-tooltip> </el-table-column>
          <el-table-column label="文件名称" align="center" width="120" prop="fileName" show-overflow-tooltip> </el-table-column>
          <el-table-column label="文件大小（KB）" align="center" width="150" prop="fileSize"> </el-table-column>
          <el-table-column label="所属批次" align="center" prop="batchName" show-overflow-tooltip> </el-table-column>
          <el-table-column label="所属组件" align="center" prop="componentNumber" show-overflow-tooltip> </el-table-column>
          <el-table-column label="所属部段" align="center" prop="sectionName"> </el-table-column>
          <el-table-column label="备注" align="center" prop="remark"> </el-table-column>
          <el-table-column label="操作" align="center" width="150" fixed="right">
            <template #default="scope">
              <el-tooltip content="预览" placement="top">
                <el-button size="small" link type="primary" icon="Edit" @click="view(scope.row)">预览</el-button>
              </el-tooltip>
              <!-- <el-tooltip content="下载" placement="top">
                <el-button size="small" link type="primary" icon="Download" @click="handleDownload(scope.row)">下载</el-button>
              </el-tooltip> -->
              <el-tooltip content="删除" placement="top">
                <el-button size="small" link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagenation">
          <el-pagination
            v-show="total > 0"
            layout="prev, pager, next,jumper"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            :total="total"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
    <AddNecessary :addVisible="addVisible" :options="treeData" :defaultInfo="defaultInfo" v-if="addVisible" @handleEvent="handleEvent" />
    <BdfPreView v-if="preViewVisible" :data="preViewParams" :preViewVisible="preViewVisible" @handleEvent="handleView" />
  </div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import AddNecessary from './components/AddNecessary.vue';
import BdfPreView from '../util/BdfPreView.vue';
import { Search } from '@element-plus/icons-vue';
import {
  getNecessaryItemsTree,
  getNecessaryItemsList,
  deleteNecessaryItems,
  deleteNecessaryItemsValidate,
  getNecessaryItemsInfo
} from '@/api/elementLibrary';
import { getStructureTreeList, getComponentListBySection } from '@/api/elementsLibrary';
const { proxy } = getCurrentInstance();
const tableData = ref([]);
const treeData = ref([]);
const modelList = ref([]);
const ids = ref([]);
const addVisible = ref(false);
const preViewVisible = ref(false);
const preViewParams = ref();
const defaultInfo = reactive({
  level1: '',
  level2: '',
  level3: '',
  level4: ''
});
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  sectionNumber: '',
  sectionName: '',
  componentNumber: '',
  batchNumber: '',
  modelNumber: '',
  orderByColumn: 'createTime',
  isAsc: 'descending'
});
const defaultProps = ref({
  label: 'name',
  code: 'mark'
});
const total = ref(0);
const uploadOp2Visible = ref(false);
const currentRow = ref(null);
const resultList = ref([]);
const loading = ref(false);
const sectionName = ref('');
const selectionList = ref([]);
const nodeLevel = ref(0);
const handleCurrentChange = (number) => {
  queryParams.value.pageNum = number;
  doQuery();
};
const loadNode = (node, resolve) => {
  if (node.level === 1 || node.level === 2) {
    resolve(node.data.children || []);
  } else if (node.level === 3) {
    let numberArr = node.data.queryIndex && node.data.queryIndex.split('::') || [];
    getComponentListBySection({
      modelNumber: numberArr[0],
      batchNumber: numberArr[1],
      sectionNumber: numberArr[2],
      needCount: true
    }).then((res) => {      
      node.children = res.data || [];      
      resolve(node.children);                                 
    });
  } else {
    resolve([]);
  }
};
// 预览
const view = (row) => {
  const { fileUrl, fileName } = row;
  preViewParams.value = { classification: 'model_management_necessary_items_data_prefix', uri: fileUrl, fileName: fileName };
  preViewVisible.value = true;
};
const handleView = () => {
  preViewVisible.value = false;
};
//查询数据列表
const doQuery = () => {
  loading.value = true;
  tableData.value = [];
  getNecessaryItemsList(queryParams.value)
    .then((res) => {
      // 处理数据
      loading.value = false;
      total.value = res?.total;
      tableData.value = res.rows;
    })
    .catch(() => {
      loading.value = false;
    });
};
// 查询左侧树结构
const getTreeDate = () => {
  getNecessaryItemsTree({ sectionName: sectionName.value }).then((res) => {
    treeData.value = res.data;
  });
};
// 右键
const rightClick = (e, data, node, comp) => {
  // if (node.level == 1) return;
  // deepFindLevelData(data.mark, node.level);
  if (node.level == 1) {
    defaultInfo.level1 = node.data.queryIndex;
    defaultInfo.level2 = '';
    defaultInfo.level3 = '';
    defaultInfo.level4 = '';
  } else if (node.level == 2) {
    defaultInfo.level1 = node.parent.data.queryIndex;
    defaultInfo.level2 = node.data.queryIndex;
    defaultInfo.level3 = '';
    defaultInfo.level4 = '';
  } else if (node.level == 3) {
    defaultInfo.level1 = node.parent.parent.data.queryIndex;
    defaultInfo.level2 = node.parent.data.queryIndex;
    defaultInfo.level3 = node.data.queryIndex;
    defaultInfo.level4 = '';
  } else if (node.level == 4) {
    defaultInfo.level1 = node.parent.parent.parent.data.queryIndex;
    defaultInfo.level2 = node.parent.parent.data.queryIndex;
    defaultInfo.level3 = node.parent.data.queryIndex;
    defaultInfo.level4 = node.data.queryIndex;
  } 
  addVisible.value = true;
};
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.id);
  selectionList.value = selection;
};
// 回调函数
const handleEvent = (data) => {
  addVisible.value = false;
  if (data?.type === 'refresh') {
    doQuery();
    getTreeDate();
  }
};
const checkDataType = (data) => {
  if (Array.isArray(data)) {
    return 'array';
  } else if (typeof data === 'object') {
    return 'object';
  }
};
const treeSelectNode = ref([]);
const findLabel = (data) => {
  if (data.parent && checkDataType(data.parent.data) === 'object') {
    findLabel(data.parent);
  }
  treeSelectNode.value.push(data.data.label);
};
// 左侧树点击事件
const treeSelect = (selected, TreeNode) => {
  nodeLevel.value = TreeNode.level;
  if (TreeNode.level == 1) {
    queryParams.value.modelNumber = TreeNode.data.mark;
    queryParams.value.batchNumber = '';
    queryParams.value.sectionNumber = '';
    queryParams.value.sectionName = '';
    queryParams.value.componentNumber = '';
    defaultInfo.level1 = TreeNode.data.queryIndex;
    defaultInfo.level2 = '';
    defaultInfo.level3 = '';
    defaultInfo.level4 = '';
    doQuery();
  } else if (TreeNode.level == 2) {
    queryParams.value.modelNumber = TreeNode.parent.data.mark;
    queryParams.value.batchNumber = TreeNode.data.mark;
    queryParams.value.sectionNumber = '';
    queryParams.value.sectionName = '';
    queryParams.value.componentNumber = '';
    defaultInfo.level1 = TreeNode.parent.data.queryIndex;
    defaultInfo.level2 = TreeNode.data.queryIndex;
    defaultInfo.level3 = '';
    defaultInfo.level4 = '';
    doQuery();  
  } else if (TreeNode.level == 3) {
    queryParams.value.modelNumber = TreeNode.parent.parent.data.mark;
    queryParams.value.batchNumber = TreeNode.parent.data.mark;
    queryParams.value.sectionNumber = TreeNode.data.mark;
    queryParams.value.sectionName = TreeNode.data.name;
    queryParams.value.componentNumber = '';
    defaultInfo.level1 = TreeNode.parent.parent.data.queryIndex;
    defaultInfo.level2 = TreeNode.parent.data.queryIndex;
    defaultInfo.level3 = TreeNode.data.queryIndex;
    defaultInfo.level4 = '';
    doQuery();
  } else if (TreeNode.level == 4) {
    queryParams.value.modelNumber = TreeNode.parent.parent.parent.data.mark;
    queryParams.value.batchNumber = TreeNode.parent.parent.data.mark;
    queryParams.value.sectionNumber = TreeNode.parent.data.mark;
    queryParams.value.componentNumber = TreeNode.data.mark;
    defaultInfo.level1 = TreeNode.parent.parent.parent.data.queryIndex;
    defaultInfo.level2 = TreeNode.parent.parent.data.queryIndex;
    defaultInfo.level3 = TreeNode.parent.data.queryIndex;
    defaultInfo.level4 = TreeNode.data.queryIndex;
    doQuery();
  } else {
    doReset();
  }
};
const doReset = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    sectionNumber: '',
    sectionName: '',
    componentNumber: '',
    modelNumber: '',
    batchNumber: '',
    orderByColumn: 'createTime',
    isAsc: 'descending'
  };
  doQuery();
};
// 打开弹窗方法
const handleVisible = (param, data) => {
  if (param != 'add') {
    const valueData = resultList.value.filter((el) => {
      return el.resultId === data.resultId;
    });
    currentRow.value = valueData[0];
  }

  switch (param) {
    case 'add': {
      defaultInfo.level1 = '';
      defaultInfo.level2 = '';
      defaultInfo.level3 = '';
      defaultInfo.level4 = '';
      addVisible.value = true;
      break;
    }
    case 'edit': {
      uploadOp2Visible.value = true;
      break;
    }
  }
};
//删除
const handleDelete = (row) => {
  const dataIds = row?.id ? [row?.id] : ids.value;
  deleteNecessaryItemsValidate(dataIds).then(async res => {
    let infoMsg = !res.data ? res.msg : (row?.id ? '是否确认删除当前数据项？' : '是否确认删除当前所选全部数据项？')
    ElMessageBox.confirm(infoMsg, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      deleteNecessaryItems(dataIds)
      .then((res) => {
        if (res) {
          ElMessage({ showClose: true, message: '删除成功。', type: 'success' });
          doQuery();
          nodeLevel.value == 1 && getTreeDate();
          nodeLevel.value > 1 && syncNecessaryItemsCount(row?.id ? [row] : selectionList.value)
        }
      })
      .catch(() => {
        ElMessage({ showClose: true, message: '删除失败。', type: 'error' });
      });
    });
  })
};
// 删除操作手动更新当前节点的必备件数
const syncNecessaryItemsCount = (list) => {
  const Item = list[0]; // c919 batch2 c919_s11 2057815715G27
  const {modelNumber, batchNumber, sectionNumber, componentNumber} = Item;
  if (nodeLevel.value == 2) {
    // 更新批次下的必备件数目
    treeData.value.forEach(item => {
      if (item.mark == modelNumber) {
        item.children && item.children.forEach(item1 => {
          if (item1.mark == batchNumber) {
            item1.necessaryItemsCount -= list.length;
          }
        })  
      }
    })
  } else if (nodeLevel.value == 3) {
    // 更新部段下的必备件数目
    treeData.value.forEach(item => {
      if (item.mark == modelNumber) {
        item.children && item.children.forEach(item1 => {
          if (item1.mark == batchNumber) {
            item1.children && item1.children.forEach(item2 => {
              if (item2.mark == sectionNumber) {
                item2.necessaryItemsCount -= list.length;
              }
            })  
          }
        })  
      }
    })
  } else if (nodeLevel.value == 4) {
    // 更新组件下的必备件数目
    treeData.value.forEach(item => {
      if (item.mark == modelNumber) {
        item.children && item.children.forEach(item1 => {
          if (item1.mark == batchNumber) {
            item1.children && item1.children.forEach(item2 => {
              if (item2.mark == sectionNumber) {
                item2.children && item2.children.forEach(item3 => {
                  if (item3.mark == componentNumber) {
                    item3.necessaryItemsCount -= list.length;
                  }
                })  
              }
            })  
          }
        })  
      }
    })
  }
}
const getModelList = () => {
  getStructureTreeList({parentId:0}).then(res => {
    modelList.value = res.rows;
  })
}
onMounted(() => {
  getModelList();
  getTreeDate();
  doQuery();
});
</script>
<style lang="scss" scoped>
.public_main {
  display: flex;
  .left_tree {
    // width: 230px;
    // overflow: auto;
    // height: calc(100vh - 155px);
    width: 270px;
    padding: 10px;
    height: calc(100vh - 84px);
    overflow: auto;
    border-right: 1px solid #dddddd7a;
  }
  .right_table {
    width: calc(100% - 270px);
    overflow: auto;
    height: calc(100vh - 155px);
    .query {
      border: 1px solid #dddddd7a;
      padding: 20px 10px 0 10px;
      .query_btns {
        padding-left: 100px;
      }
    }
    .table_div {
      margin-top: 10px;
      border: 1px solid #dddddd7a;
      padding-bottom: 10px;
      .upload_btn {
        margin: 10px 10px;
      }
      .pagenation {
        display: flex;
        justify-content: end;
        margin-top: 10px;
      }
    }
  }
  .custom-tree-node {
    font-size: 12px;
    color: #606266;
  }
  :deep(.el-form-item__content) {
    width: 220px;
  }
}
</style>
  